#ifndef __EVENTLOOP_H_
#define __EVENTLOOP_H_
#include"Acceptor.h"
#include"Noncopyable.h"
#include"TcpConnection.h"
#include"Mutexlock.h"
#include<sys/epoll.h>
#include<sys/eventfd.h>
#include<vector>
#include<functional>
#include<map>
#include<memory>
#include<assert.h>
#include<unistd.h>

using std::vector;
using std::map;

namespace SC
{
    
    class TcpConnection;
    using TcpConnectionPtr = std::shared_ptr<TcpConnection>;
    using TcpConnectionCallBack = std::function<void(const TcpConnectionPtr&)>;
    using Func = std::function<void()>;

    class EventLoop : Noncopyable
    {
    public:
        EventLoop(Acceptor&);

        void Loop();
        void Unloop();
        void runInLoop(Func&&);

        void setConnectCB(const TcpConnectionCallBack&);
        void setMessageCB(const TcpConnectionCallBack&);
        void setCloseCB(const TcpConnectionCallBack&);

    private:
        int createEpollfd();
        void wait();
        void add(int);
        void del(int);
        bool isQuit(int);
        void handleConnection();
        void handleMessage(int);
        
        int createEventfd();
        void handleRead();
        void wake();
        void doPendingFuncs();
    
    private:
        int _epfd;
        int _eventfd;
        Acceptor &_acceptor;
        bool _isLoop;
        Mutexlock _mutex;
        vector<epoll_event> _events;
        vector<Func> _funcs;
        map<int, TcpConnectionPtr> _connections;
        

        TcpConnectionCallBack _cb_connection;
        TcpConnectionCallBack _cb_msg;
        TcpConnectionCallBack _cb_close;
    };
}
#endif